from flask import Blueprint, jsonify, request
import json
from db import db1

bp_admin = Blueprint('admin', __name__)


def get_data():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    return data


@bp_admin.route('/roles', methods=['POST', 'GET'])
def roles():
    if request.method == 'POST':
        data = get_data()
        sql1 = '''select id from roles where name = "%s" ''' % (data['name'])
        res1 = db1.findall(sql1)
        if res1:
            return jsonify({'code': 20010, 'mes': '该角色已存在'})
        else:
            sql = '''insert into roles values(0,"%s")''' % (data['name'])
            db1.update(sql)
            return jsonify({'code': 200})
    elif request.method == 'GET':
        sql1 = '''select * from roles'''
        res1 = db1.findall(sql1)
        sql2 = '''select * from resources'''
        res2 = db1.findall(sql2)
        return jsonify({'code': 200, 'list1': res1, 'list2': res2})


@bp_admin.route('/resources', methods=['POST'])
def resources():
    if request.method == 'POST':
        data = get_data()
        sql1 = '''select id from resources where name = "%s" ''' % (data['name'])
        res1 = db1.findall(sql1)
        if res1:
            return jsonify({'code': 20010, 'mes': '该资源已存在'})
        else:
            sql = '''insert into resources values(0,"%s","%s")''' % (data['name'], data['url'])
            db1.update(sql)
            return jsonify({'code': 200})


@bp_admin.route('/jszy', methods=['POST', 'GET'])
def jszy():
    if request.method == 'POST':
        data = get_data()
        sql = '''delete from role_resources where role_id = %d ''' % (int(data['role_id']))
        db1.update(sql)
        ids = data['ids']
        for i in ids:
            sql = '''insert into role_resources values(0,%d,%d,%d)''' % (int(data['role_id']), i, 1)
            db1.update(sql)
        return jsonify({'code': 200})
    elif request.method == 'GET':
        id = request.args.get('id')

        sql = '''select resources_id from role_resources where role_id = %d ''' % (int(id))
        res = db1.findall(sql)
        list1 = []
        for i in res:
            list1.append(i['resources_id'])
        print(list1)
        return jsonify({'code': 200, 'idlist': list1})


@bp_admin.route('/user', methods=['POST'])
def user():
    if request.method == 'POST':
        data = get_data()
        sql = '''select id from admin_user where name = "%s" ''' % (data['name'])
        res = db1.findall(sql)
        if res:
            return jsonify({'code': 20010, 'mes': '手机号已存在'})
        else:
            sql = '''insert into admin_user values(0,"%s","%s",%d,%d)''' % (
                data['name'], "123", 1, int(data['role_id']))
            db1.update(sql)
            return jsonify({'code': 200})



from utils.rediscoon import r
from utils.sendsms import send_message
import random
import re
from utils.jwttoken import myjwt

@bp_admin.route('/send', methods=['GET','POST'])
def send():
    if request.method == 'GET':
        mobile = int(request.args.get('mobile'))
        if not re.match('^1[3-9]\d{9}$', str(mobile)):
            return jsonify({'code': 20010, 'ts': '手机号错误'})
        value = r.get_str(mobile)
        if value:
            return jsonify({'code': 10011, 'ts': '验证码已发送，请1分钟后再试'})

        codess = random.randint(100000, 999999)
        flag = send_message(mobile, codess, 1)
        if flag:
            r.set_str(mobile, codess, 60)
            return jsonify({'code': 200})
        else:
            return jsonify({'code': 20012, 'ts': '验证码发送失败'})
    elif request.method == 'POST':
        # 手机号、验证码发起请求 -》根据手机号去redis中取验证码 -》没取到直接返回
        # redis取出来的验证码，输入的对比 -》对比成功 -》去数据库查询 -》手机号存在 -》生成token返回
        data = get_data()
        value = r.get_str(data['mobile'])
        if not value:
            return jsonify({'code':20013,'mes':'验证码不存在'})
        if int(value) == int(data['codes']):

            sql = 'select * from admin_user where name = "%s" '%(data['mobile'])
            print(sql)
            res = db1.findone(sql)
            print(res)
            if res:
                token = myjwt.encode_jwt(data)
                r.del_str(data['mobile'])
                return jsonify({'code':200,'token':token})
            else:
                return jsonify({'code':20014,'mes':'用户不存在'})
        else:
            return jsonify({'code':20015,'mes':'验证码错误'})



